package com.suny.sf_server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.suny.DataDic.vo.DataDicVO;
import com.suny.constant.RedisKeyConstant;
import com.suny.result.PageDTO;
import com.suny.result.ResponseCode;
import com.suny.sf_server.redis.IRedisService;
import com.suny.utils.BeanConverter;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import com.suny.DataDic.DataDic;
import com.suny.sf_server.service.DataDicService;
import com.suny.sf_server.mapper.DataDicMapper;
import org.springframework.stereotype.Service;
import com.suny.DataDic.dto.DataDicDTO;
import com.suny.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import com.suny.DataDic.dto.DataDicQueryDTO;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
* @author sun
* @description 针对表【data_dic(牲畜品种信息表)】的数据库操作Service实现
* @createDate 2024-12-27 10:45:10
*/
@Service
@Slf4j
public class DataDicServiceImpl extends ServiceImpl<DataDicMapper, DataDic>
    implements DataDicService{
    @Resource
    private ValidationService validationService;

    @Resource
    private IRedisService redisService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addDataDic(DataDicDTO dataDicDTO) {
        if (dataDicDTO.getName() == null||dataDicDTO.getName().trim().isEmpty()){
            throw new BusinessException("字典名称不能为空");
        }

        DataDic dataDic = new DataDic();
        dataDic.setName(dataDicDTO.getName());
        dataDic.setStatus(1);
        dataDic.setCreatedTime(new Date());
        dataDic.setUpdatedTime(new Date());
        
        int count = baseMapper.insert(dataDic);
        if (count == 0) {
            throw new BusinessException("添加失败");
        }
        
        // 清除字典列表缓存
        clearCache();
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateStatus(Integer dicId, Integer status) {
        if (dicId == null || status == null) {
            throw new BusinessException(ResponseCode.ILLEGAL_PARAMETER.getInfo());
        }
        
        if (status != 1 && status != 0) {
            throw new BusinessException("状态值无效");
        }
        DataDic dic = getById(dicId);
        if (dic == null) {
            throw new BusinessException("数据字典不存在");
        }
        if (Objects.equals(dic.getStatus(), status)) {
            throw new BusinessException("状态值未改变");
        }

        // 检查是否有数据字典值
        if (status == 0 && validationService.hasDataDicVal(dicId)) {
            throw new BusinessException("该数据字典下有数据字典值，不能停用");
        }
        
        LambdaQueryWrapper<DataDic> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DataDic::getId, dicId);
        DataDic dataDic = new DataDic();
        dataDic.setStatus(status);
        dataDic.setUpdatedTime(new Date());
        
        boolean success = update(dataDic, wrapper);
        if (!success) {
            throw new BusinessException("更新失败");
        }
        
        // 清除相关缓存
        clearCache();
        return true;
    }
    
    @Override
    public Page<DataDic> getList(PageDTO pageDTO) {
        // 1. 参数校验
        if (pageDTO == null || pageDTO.getPageNumber() <= 0 || pageDTO.getPageSize() <= 0) {
            throw new BusinessException(ResponseCode.ILLEGAL_PARAMETER.getInfo());
        }
        
        // 2. 生成包含分页参数的缓存key
        String cacheKey = String.format("%s:%d:%d", 
            RedisKeyConstant.DIC_LIST,
            pageDTO.getPageNumber(),
            pageDTO.getPageSize());
        
        // 3. 尝试从缓存获取
        if (redisService.isExists(cacheKey)) {
            return redisService.getValue(cacheKey);
        }
        
        // 4. 查询数据库
        Page<DataDic> page = new Page<>(pageDTO.getPageNumber(), pageDTO.getPageSize());
        LambdaQueryWrapper<DataDic> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(DataDic::getCreatedTime);
        Page<DataDic> resultPage = page(page, wrapper);
        
        // 5. 处理空结果缓存
        if (resultPage != null && resultPage.getTotal() > 0) {
            redisService.setValue(cacheKey, resultPage, RedisKeyConstant.CACHE_TIME);
        } else {
            redisService.setValue(cacheKey, resultPage, RedisKeyConstant.EMPTY_CACHE_TIME);
        }
        
        return resultPage;
    }

    @Override
    public Page<DataDic> getListByCondition(DataDicQueryDTO query) {
        // 1. 参数校验
        if (query == null || query.getPageSize() == null || query.getPageNumber() == null) {
            throw new BusinessException(ResponseCode.ILLEGAL_PARAMETER.getInfo());
        }

        // 2. 生成包含查询条件的缓存key
        String cacheKey = String.format("%s:%s:%d:%d",
            RedisKeyConstant.DIC_LIST,
            query.hashCode(),
            query.getPageNumber(),
            query.getPageSize());

        // 3. 尝试从缓存获取
        if (redisService.isExists(cacheKey)) {
            return redisService.getValue(cacheKey);
        }

        // 4. 查询数据库
        Page<DataDic> page = new Page<>(query.getPageNumber(), query.getPageSize());
        IPage<DataDic> voPage = baseMapper.selectDataDicVOPageByCondition(page, query);

        // 5. 处理空结果缓存
        if (voPage != null && voPage.getTotal() > 0) {
            redisService.setValue(cacheKey, voPage, RedisKeyConstant.CACHE_TIME);
        } else {
            redisService.setValue(cacheKey, voPage, RedisKeyConstant.EMPTY_CACHE_TIME);
        }

        return (Page<DataDic>) voPage;
    }

    @Override
    public List<DataDicVO> getBySelect() {
        LambdaQueryWrapper<DataDic> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DataDic::getStatus, 1);
        List<DataDic> list = baseMapper.selectList(wrapper);
        if (list == null && list.isEmpty()) {
           throw new BusinessException("数据字典为空");
        }
        return BeanConverter.convertList(list, DataDicVO.class);
    }

    /**
     * 清除数据字典相关缓存
     */
    private void clearCache() {
        // 使用模式匹配删除所有数据字典列表缓存
        redisService.removePattern(RedisKeyConstant.DIC_LIST + ":*");
    }
}




